package com.zhou.framework.util;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.zhou.framework.model.PageParam;
import com.zhou.framework.model.PageResult;
import com.zhou.util.StringTool;

import java.util.List;

/**
 * @author lang.zhou
 * @date 2022/5/6 12:49
 */
public class PageUtil {

    public static void offsetPage(PageParam config){
        PageHelper.offsetPage(config.getOffset(),config.getLimit());
        if(StringTool.isNotBlank(config.getOrderColumn())){
            StringBuilder orderBy = new StringBuilder();
            orderBy.append(CamelUtil.camel2underline(config.getOrderColumn()));
            if(StringTool.isNotBlank(config.getOrderType())){
                orderBy.append(" ").append(config.getOrderType().replace("ending",""));
            }
            PageHelper.orderBy(orderBy.toString());
        }
    }
    public static void orderBy(String orderBy){
        PageHelper.orderBy(orderBy);
    }

    public static <T> PageResult<T> result(PageParam dto, List<T> list, long total){
        PageResult<T> res = new PageResult<T>(dto);
        res.setList(list);
        res.setTotal(total);
        return res;
    }

    public static <T> PageResult<T> result(PageParam dto, List<T> list){
        PageResult<T> res = new PageResult<T>(dto);
        PageInfo<T> info = new PageInfo<>(list);
        res.setList(list);
        res.setTotal(info.getTotal());
        return res;
    }

    public static <T> PageResult<T> logicResult(PageParam dto, List<T> list){
        int from = Math.min(dto.getFrom(),list.size());
        int to = Math.min(dto.getTo(),list.size());
        PageResult<T> res = new PageResult<T>(dto);
        res.setList(list.subList(from,to));
        res.setTotal((long) list.size());
        return res;
    }

    public static <T> PageResult<T> result(PageResult<T> res, List<T> list){
        PageInfo<T> info = new PageInfo<>(list);
        res.setList(list);
        res.setTotal(info.getTotal());
        return res;
    }
}
